package sdu.attendancechecker.services;

import java.util.Properties;
import java.util.Random;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class PasswordService {

	/*
	 * Random String generator specify Password length, by default 10
	 */
	public static String generatePassword() {
		int passwordLen = 10;
		String symbols = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
		Random random = new Random();
		StringBuilder passwordBuilder = new StringBuilder(passwordLen);
		for (int i = 0; i < passwordLen; i++) {
			int index = random.nextInt(symbols.length());
			passwordBuilder.append(symbols.charAt(index));
		}
		String password = passwordBuilder.toString();
		return password;
	}

	public static void sendPasswordTo(String email, String newpass) {
		final String username = "altynbek.nurgaziyev@gmail.com";
		final String password = "Altynbekmyrza";
		Properties props = new Properties();
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.socketFactory.port", "465");
		props.put("mail.smtp.socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", "465");
		Session session = Session.getInstance(props,
				new javax.mail.Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(username, password);
					}
				});
		try {
			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress("altynbek.nurgaziyev@gmail.com"));
			message.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(email));
			message.setSubject("Reset Password");
			message.setText("Your new password: " + newpass);
			Transport.send(message);
		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}
	}
}
